package com.demo.server;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.demo.dao.IUserLogDao;
import com.demo.entity.MeUser;
import com.demo.entity.MeUserLog;
import com.demo.entity.enu.DoTypeEnum;
import com.demo.support.Interceptor.JHandleInter;
import com.jweb.annotaion.JAutowired;
import com.jweb.core.JWebFilter;
import com.jweb.util.FormatUtil;
import com.jweb.util.HttpServletRequestUtil;
import com.jweb.util.ThreadPoolUtil;
import com.jweb.util.WebUtil;

/**
 * 用户操作日志记录
 * 
 * @author Yuanqy
 *
 */
public class UserLogServer {
	Logger log = LoggerFactory.getLogger(getClass());

	private @JAutowired IUserLogDao dao;

	/**
	 * 登录前记录日志
	 */
	public void asynAddUserLog(HttpServletRequest req, DoTypeEnum enu, Long userId) {
		final MeUserLog ulog = new MeUserLog(userId, enu.getType(), "", enu.getRemark(), HttpServletRequestUtil.getIp(req));
		asynAddUserLog(ulog);
	}

	/**
	 * 登录后记录日志
	 */
	public void asynAddUserLog(HttpServletRequest req, DoTypeEnum enu) {
		try {
			MeUser u = (MeUser) WebUtil.getSessionAttribute(req, JHandleInter.USER);
			final MeUserLog ulog = new MeUserLog(u.getUserId(), enu.getType(), "", enu.getRemark(), HttpServletRequestUtil.getIp(req));
			asynAddUserLog(ulog);
		} catch (Exception e) {
			log.error("用户未登录，不能使用该方法记录日志", e);
		}

	}

	/**
	 * 公共记录日志
	 * 
	 * @param ulog
	 */
	public void asynAddUserLog(final MeUserLog ulog) {
		ThreadPoolUtil.execute(new Thread("新增用户操作日志") {
			@Override
			public void run() {
				try {
					if (dao.add(ulog) > 0) {
						log.info("==异步用户操作日志记录完成");
					} else {
						log.error("==异步用户操作日志记录失败：" + FormatUtil.toJSONString(ulog));
					}
				} catch (Exception e) {
					log.error("==异步用户操作日志记录失败", e);
				}
			}
		});
	}
}
